<template>
  <div class="leave-balance-container">
    <el-descriptions
      v-if="leaveBalance"
      :column="2"
      size="medium"
      border
      title="假期余额"
    >
      <el-descriptions-item label="工作年限">
        {{ leaveBalance.workYear || '0' }}
      </el-descriptions-item>
      <el-descriptions-item label="年假总时长">
        {{ leaveBalance.annualLeave || '0' }}
      </el-descriptions-item>

      <el-descriptions-item label="剩余年假">
       {{ leaveBalance.remainingAnnualLeave || '0' }}
      </el-descriptions-item>

      <el-descriptions-item label="剩余事假">
        {{ leaveBalance.remainingPersonalLeave || '0' }}
      </el-descriptions-item>
      <el-descriptions-item label="剩余病假">
        {{ leaveBalance.remainingSickLeave || '0' }}
      </el-descriptions-item>
      <el-descriptions-item label="剩余婚假">
        {{ leaveBalance.remainingMarriageLeave || '0' }}
      </el-descriptions-item>
      <el-descriptions-item label="剩余产假">
        {{ leaveBalance.remainingMaternityLeave || '0' }}
      </el-descriptions-item>
      <el-descriptions-item label="剩余陪产假">
        {{ leaveBalance.remainingFaternityLeave || '0' }}
      </el-descriptions-item>
      <el-descriptions-item label="剩余加班假">
        {{ leaveBalance.remainingOvertimeLeave || '0' }}
      </el-descriptions-item>
      <el-descriptions-item label="剩余其他假">
        {{ leaveBalance.remainingOthersLeave || '0' }}
      </el-descriptions-item>
    </el-descriptions>

    <el-alert
      v-else
      type="info"
      :closable="false"
      title="暂无假期余额信息"
      style="margin-top: 20px;"
    />
  </div>
</template>

<script>
import { getBalanceByEmpId } from "@/api/leave/balance";

export default {
  name: 'LeaveBalance',
  props: {
    empId: {
      type: Number,
      required: true // 必须传 empId
    }
  },
  data() {
    return {
      leaveBalance: null,
      loading: false
    };
  },
  watch: {
    empId: {
      immediate: true,
      handler(newEmpId) {
        console.log('LeaveBalance 接收到的 empId:', newEmpId); // 调试用
        if (newEmpId && typeof newEmpId === 'number') {
          this.loadBalance();
        } else {
          this.leaveBalance = null;
          console.warn('无效的 empId，跳过加载假期数据');
        }
      }
    }
  },
  methods: {
    async loadBalance() {
      this.loading = true;
      try {
        const res = await getBalanceByEmpId(this.empId);

        // 👇 关键修复：从数组取第一个元素
        if (Array.isArray(res.data) && res.data.length > 0) {
          this.leaveBalance = res.data[0];
        } else if (res.data && typeof res.data === 'object') {
          this.leaveBalance = res.data; // 兼容未来返回对象的情况
        } else {
          this.leaveBalance = null;
        }

      } catch (error) {
        console.error("加载假期余额失败:", error);
        this.$message.error("假期信息加载失败");
        this.leaveBalance = null;
      } finally {
        this.loading = false;
      }
    }
  }
}
</script>

<style scoped>
.leave-balance-container {
  padding: 16px;
}
</style>
